package com.heima.wemedia.gateway.filter;

import com.heima.wemedia.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 配置全局过滤器
 */
@Component
public class AuthorizeFilter implements GlobalFilter,Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1，获取请求头信息
        ServerHttpRequest request = exchange.getRequest();

        //2，获取响应头信息
        ServerHttpResponse response = exchange.getResponse();

        //3，判断用户是否为登录，如果是登录，进入登录页面，放行
        String path = request.getURI().getPath();
        //根据路径判断
        if(path.startsWith("/wemedia/login/in")){
           return chain.filter(exchange);
        }

        //4，如果不是用户登录，获取token，
        String token = request.getHeaders().getFirst("token");

        //判断token是否存在，如果不存在返回401
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //5，如果token存在，校验token是否正确，获取用户id信息，把id信息设置到头中
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claimsBody);
            if(result==0 || result==-1){
                //如果校验成功，请求放行，从载荷中获取id信息，
                String userId = claimsBody.get("id") + "";
                //放在请求头中,方便后边微服务调用
                request.mutate().header("userId",userId);
                return chain.filter(exchange);
            }else {
                //校验不存在，401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

        } catch (Exception e) {

            //6，如果jwt解析抛出异常，响应401
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        //值越小，代表级别越高
        return 0;
    }
}
